<!-- 
 
-->
<template>
  <div class="time-slider-wrap" :class="{ 'is-down': isDragging }" @mousedown="handleMouseDown" @mousemove="handleMouseMove" @mouseup="handleMouseUp">
    <template v-for="(item, idx) in timeMarks">
      <div class="cell" v-if="idx !== timeMarks.length - 1" :key="idx" :class="{ selected: item.active, begin: item.isBegin, end: item.isEnd, rest: item.isRest, rest2: item.isRest2, disabled: item.isDisabled }">
        {{ item.label }}-{{ item.active }}

        <div class="red-line start" v-if="item.isBegin" :style="{ top: item.locBegin }"></div>
        <div class="red-line end" v-if="item.isEnd" :style="{ top: item.locEnd }"></div>
        <div class="red-line rest" v-if="item.isRest" :style="{ top: item.locRest }"></div>
        <div class="red-line rest" v-if="item.isRest2" :style="{ top: item.locRest2 }"></div>
      </div>
    </template>
    <div class="line"></div>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import IProjectTypes from '../../interface/IProjectTypes'

const timeMarks = ref<any[]>([])
const selectedCells = ref<any[]>([]) // 用于存储被选中的单元格
const isDragging = ref(false)
const startCell = ref<any>(null) // 用于存储鼠标按下时选中的单元格
const endCell = ref<any>(null) // 用于存储鼠标移动时当前选中的单元格

const props = defineProps({
  today: {
    type: String || Date,
    required: true,
    default: '',
  },

  timeDates: {
    type: Array,
    required: true,
    default: () => [],
  },
  beginTime: {
    type: String,
    default: '08:00',
  },
  endTime: {
    type: String,
    default: '17:00',
  },
  startLunchTime: {
    type: String,
    default: '12:00',
  },
  endLunchTime: {
    type: String,
    default: '13:00',
  },
  disabledTimes: {
    type: Array,
    required: true,
    default: () => [],
  },
  logList: {
    type: Array<any>,
    required: true,
  },
  timelogCategory: {
    type: Array<IProjectTypes>,
    required: true,
    default: () => [{ dictCode: 0 }],
  },
})

onMounted(async () => {
  // console.log('！===== onMounted', props.logList)
  initMarks()
  updateMarks()
  // console.log('！===== onMounted timeMarks', timeMarks)
})

/**
 * 初始化标记
 *
 * 该函数用于初始化marks数组，将timeDates数组中的每个元素转换为对象并推入marks数组中
 *
 * @returns 无返回值
 */
const initMarks = () => {
  // console.log('initMarks')
  let i = 0
  timeMarks.value = []
  const hasBegin = props.timeDates.indexOf(props.beginTime)
  const hasEnd = props.timeDates.indexOf(props.endTime)
  const hasRest = props.timeDates.indexOf(props.startLunchTime)
  const hasRest2 = props.timeDates.indexOf(props.endLunchTime)
  props.timeDates.forEach((item: any) => {
    const idx = props.disabledTimes.findIndex((e) => e == item)
    let isBegin = props.beginTime == item
    let isEnd = props.endTime == item
    let locBegin = '0'
    let locEnd = '0'
    let isRest = false
    let locRest = '0'
    let isRest2 = false
    let locRest2 = '0'

    if (hasRest == -1 && item.slice(0, 2) === props.startLunchTime.slice(0, 2)) {
      locRest = (parseInt(props.startLunchTime.slice(-2)) / 60) * 100 + '%'
      isRest = true
    } else if (hasRest > -1 && item.slice(0, 2) === props.startLunchTime.slice(0, 2)) {
      locRest = '0%'
      isRest = true
    }
    if (hasRest2 == -1 && item.slice(0, 2) === props.endLunchTime.slice(0, 2)) {
      locRest2 = (parseInt(props.endLunchTime.slice(-2)) / 60) * 100 + '%'
      isRest2 = true
    } else if (hasRest2 > -1 && item.slice(0, 2) === props.endLunchTime.slice(0, 2)) {
      locRest = '0%'
      isRest = true
    }

    if (hasBegin == -1 && item.slice(0, 2) === props.beginTime.slice(0, 2)) {
      isBegin = true
      locBegin = (parseInt(props.beginTime.slice(-2)) / 60) * 100 + '%'
    }

    if (hasEnd == -1 && item.slice(0, 2) === props.endTime.slice(0, 2)) {
      isEnd = true
      locEnd = (parseInt(props.endTime.slice(-2)) / 60) * 100 + '%'
    }
    // if (props.beginTime == '08:00') {
    //   // startWorkTime
    //   // 长春
    //   isEnd = item == '16:00'
    //   locEnd = '83.3%'
    // } else if (props.beginTime == '09:00') {
    //   // 北京
    // }
    timeMarks.value.push({ id: i, label: item, active: false, value: item, isDisabled: idx > -1, isBegin, isEnd, locBegin, locEnd, isRest, locRest, locRest2, isRest2 })
    i++
  })
  // console.log('startWorkTime', startWorkTime)
  // console.log('endWorkTime', endWorkTime)
  // console.log('hasBegin', hasBegin)
  // console.log('hasEnd', hasEnd)
  // console.log('marks', marks)
}

/**
 * 更新标记状态
 *
 * 根据当前日志列表和今天的时间，更新标记数组marks的状态。
 * 对于marks数组中的每一个元素，会筛选出日志列表中开始时间（不包含秒数）与当前时间和标记时间（不包含秒数）一致的日志条目，
 * 并将这些日志条目作为子元素赋值给当前元素的children属性。
 * 同时，设置当前元素的active属性为false，isDisabled属性根据子元素的长度决定（如果有子元素则为true，否则为false），
 * 如果子元素长度大于3，则设置overflow属性为子元素长度减去3的值，否则不设置overflow属性。
 */
const updateMarks = () => {
  // console.log('updateMarks')
  timeMarks.value.map((item: any) => {
    const cells = props.logList.filter((e) => e.startTime.slice(0, -2) === props.today + ' ' + item.value.slice(0, -2))
    item.children = cells
    item.active = false
    item.isDisabled = cells.length > 0
    if (cells.length > 0) {
      item.overflow = cells.length - 3
    }
  })
}

const handleMouseDown = (event: any) => {
  event.preventDefault() // 阻止默认的鼠标按下行为
  isDragging.value = true // 设置拖拽状态为 true
  selectedCells.value = [] // 清空已选中的单元格

  const cell = findCellFromEvent(event) // 查找鼠标按下时选中的单元格
  if (cell) {
    startCell.value = cell // 设置起始单元格
    endCell.value = cell // 设置结束单元格（初始时与起始单元格相同）
    cell.isChecked = true // 选中该单元格
    selectedCells.value = [cell] // 将该单元格添加到已选中的单元格列表中
  }
}
const handleMouseMove = (event: any) => {
  if (isDragging.value && startCell.value) {
    // 查找鼠标当前位置下的单元格
    const currentCell = findCellFromEvent(event)
    if (currentCell && currentCell !== endCell) {
      endCell.value = currentCell // 更新结束单元格
      updateSelectedCells() // 更新已选中的单元格列表
    }
  }
}

const handleMouseUp = () => {
  isDragging.value = false // 重置拖拽状态为 false
  timeMarks.value.map((e) => (e.active = false))
  console.log('startCell', startCell.value)
  console.log('endCell', endCell.value)
}

// 查找鼠标事件对应的单元格
const findCellFromEvent = (event: MouseEvent): any | null => {
  const cells = Array.from(document.querySelectorAll('.cell')) as HTMLElement[]
  const targetCell = cells.find((cell) => {
    const rect = cell.getBoundingClientRect()
    return event.clientX >= rect.left && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom
  })
  const cellName = targetCell?.textContent?.split('-')[0]
  return cellName ? timeMarks.value.find((cell) => cell.value === cellName) ?? null : null
}

// 更新已选中的单元格列表
const updateSelectedCells = () => {
  if (!startCell || !endCell) return
  const startIndex = timeMarks.value.findIndex((e) => e.id == startCell.value.id)
  const endIndex = timeMarks.value.findIndex((e) => e.id == endCell.value.id)
  const [start, end] = startIndex < endIndex ? [startIndex, endIndex] : [endIndex, startIndex]
  selectedCells.value = timeMarks.value.slice(start, end + 1)
  timeMarks.value.forEach((cell, index) => {
    cell.active = index >= start && index <= end
  })
}
</script>
<style lang="scss" scoped>
.time-slider-wrap {
  position: relative;
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  border-bottom: 1px solid #e4e7ed;
  &.is-down {
    .cell {
      &:after {
        opacity: 1;
        display: block;
      }
      &:hover {
        background-color: rgba(0, 0, 0, 0);
      }
      &.selected {
        // background-color: #337ecc;
        &:after {
          opacity: 0;
          display: none;
        }
      }
    }
  }
  .cell {
    display: flex;
    flex: 1;
    border-top: 1px solid #e4e7ed;
    align-items: self-start;
    position: relative;
    background-color: #fff;
    &:after {
      content: '';
      opacity: 0;
      display: none;
      position: absolute;
      pointer-events: none;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(0, 0, 0, 0.2);
    }

    &.checked {
      background-color: #337ecc;
    }
    &.begin,
    &.end,
    &.rest,
    &.rest2 {
      .red-line {
        display: block;
      }
      // border-top: 2px solid #ff0000;
    }
    &.disabled {
      color: #337ecc;
      background-color: #ecf5ff;
      &:hover {
        background-color: #ecf5ff;
      }
    }
    &.selected {
      // background-color: #337ecc;
      &:after {
        opacity: 0;
        display: none;
      }
    }
    .red-line {
      display: none;
      pointer-events: none;
      position: absolute;
      right: 0;
      left: 0;
      height: 2px;
      background-color: #c45656;
      &.rest,
      &.rest2 {
        background-color: transparent;
        height: 0px;
        // border-style: dotted;
        border-bottom: 1px dashed rgb(248, 152.1, 152.1);
        border-bottom-style: dashed;
      }
    }
    .time {
      width: 60px;
      user-select: none;
    }
    .cell-bd {
      display: flex;
      flex: 1;
      height: 100%;
      // pointer-events: none;
      overflow: hidden;
      .time-slider-cells {
        flex: 1;
        text-align: left;
        padding: 0 10px;
        font-size: 14px;
      }
      .btn-group {
        justify-content: center;
        align-items: center;
        display: flex;
        transform: translate(100%, 0);
        transition: transform 0.1s linear 0.2s;
        .btn-cell {
          width: 70px;
          background-color: #f56c6c;
          color: #fff;
          height: 100%;
          font-size: 24px;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
      &:hover {
        .btn-group {
          transform: translate(0, 0);
          .btn-cell {
          }
        }
      }
    }
    &:last-child {
    }
  }

  .line {
    position: absolute;
    left: 60px;
    top: 0;
    bottom: 0%;
    border-left: 1px solid #e4e7ed;
    pointer-events: none;
  }
  .work-line {
    position: absolute;
    width: 100%;
    height: 0;
    left: 0;
    opacity: 0.5;
    pointer-events: none;
    border-bottom: 1px dashed rgba(255, 0, 0, 0.5);

    &.begin {
      top: 10%;
    }
    &.end {
      top: 70%;
    }
    &.job {
      top: 55%;
      border-bottom: 2px solid rgba(255, 0, 0, 1);
    }
  }
}
</style>
